<template>
	<DialogBox v-model:visible="drawerVisible" :title="`${drawerProps.title}角色`" width="750px">
		<el-form
			v-if="drawerVisible"
			ref="ruleFormRef"
			label-width="100px"
			label-suffix=" :"
			:rules="rules"
			:disabled="drawerProps.isView"
			:model="drawerProps.rowData"
			:hide-required-asterisk="drawerProps.isView"
		>
			<el-form-item label="角色名称" prop="roleName">
				<el-input v-model="drawerProps.rowData!.roleName" placeholder="请填写角色名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="备注信息" prop="remark">
				<el-input v-model="drawerProps.rowData!.remark" type="textarea" placeholder="请填写备注" clearable></el-input>
			</el-form-item>
			<el-form-item label="角色菜单" class="relative">
				<div class="absolute" style="top: 30px; left: -85px">
					<el-link type="primary" @click="changeSelectMenu('all')">全选</el-link>
					<span class="p-1">|</span>
					<el-link type="primary" @click="changeSelectMenu('clean')">取消</el-link>
				</div>
				<TreeFilter
					ref="menuTreeEl"
					v-if="drawerVisible"
					class="h-96 w-full"
					multiple
					:requestApi="getAllMenuList"
					id="id"
					label="menuName"
					:dataCallback="dataCallback"
					:defaultValue="checkedList"
					:isCheckStrictly="isCheckStrictly"
					@change="changeMenuId"
					@tree-ref-mounted="isCheckStrictly = false"
				/>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="drawerVisible = false">取消</el-button>
			<el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
		</template>
	</DialogBox>
</template>

<script setup lang="ts" name="UserDrawer">
import { getRoleMenuList } from "@/api/modules/role";
import { getAllMenuList } from "@/api/modules/user";
import DialogBox from "@/components/DialogBox";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { showTips } from "@/utils/util";
import { FormInstance } from "element-plus";
import { TreeNodeData } from "element-plus/es/components/tree/src/tree.type";
import { reactive, ref } from "vue";
import { RoleModel } from "../interface";

const rules = reactive({
	roleName: [{ required: true, message: "请填写角色名称" }]
});
interface DrawerProps {
	title: string;
	isView: boolean;
	rowData?: RoleModel;
	api?: (params: any) => Promise<any>;
	getTableList?: () => Promise<any>;
}

// drawer框状态
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: ""
});
const menuTreeEl = ref();
function changeSelectMenu(type: "all" | "clean") {
	let dataList: TreeNodeData[] = [];
	function getIdList(list: any[]) {
		list.forEach((item: any) => {
			dataList.push(item);
			if (item.children && item.children.length) {
				getIdList(item.children);
			}
		});
	}
	getIdList(menuTreeEl.value.treeData);
	menuTreeEl.value?.handleAllChecked(dataList, type == "all");
}

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps): Promise<void> => {
	drawerProps.value = params;
	await getCheckedMenuList();
	drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			drawerProps.value.rowData!.menuIds = checkedList.value.join(",");
			let { code } = await drawerProps.value.api!(drawerProps.value.rowData);
			let ok = showTips(code, drawerProps.value.rowData?.id ? "修改角色" : "添加角色");
			// ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
			if (ok) {
				drawerProps.value.getTableList!();
				drawerVisible.value = false;
			}
		} catch (error) {
			console.log(error);
		}
	});
};
// dataCallback 是对于返回的表格数据做处理，
const dataCallback = (data: any) => {
	return data.records.children;
};
//获取角色菜单权限
const checkedList = ref<any>([]);
const isCheckStrictly = ref<boolean>();
const getCheckedMenuList = async () => {
	if (drawerProps.value.rowData) {
		let { result } = await getRoleMenuList(drawerProps.value.rowData.id);
		checkedList.value = result;
		isCheckStrictly.value = true;
	}
};

//勾选菜单返回数据
const changeMenuId = (data: any) => {
	checkedList.value = [...data.checked, ...data.halfChecked].map(item => item.id);
};
defineExpose({
	acceptParams
});
</script>

<style lang="scss" scoped>
:deep(.el-tree) {
	.el-tree-node__content {
		height: 20px !important;
	}
}
:deep(.filter) {
	padding: 0;
	margin-right: 0;
}
:deep(.el-form-item:last-child) {
	margin-bottom: 0;
}
</style>
